define([
    "UtilDir/util",
    "UtilDir/tool",
    "UtilDir/org/selectOrg",
    "UtilDir/searchBlock",
    "static/app/fxpg/util/js/bootstrap-select",
    "static/app/fxpg/util/js/defaults-zh_CN",
    "Date", "DateCN", "css!DateCss",
    "EasyUI", "EasyUI-lang"
], function (Util, Tool, SelectOrg, SearchBlock) {
    /**
     * 市县救援点
     */
    var sysPath = getServer() + "/static/app/fxpg/fxRescue";

    var fxRescueFormHtml = sysPath + "/views/fxRescueForm.html";
    var getFxRescueController = function () {
        return getServer() + "/fxRescues";
    };

    /**
     * 页面初始化
     */
    var init = function () {
        initSearchBlock();
        queryBtnBind();
        initProvinceSelect();
        initCityCountyNameConditionSelect();
        initSurveySpotNameConditionSelect();
        createFxRescueGrid();
    };

    /**
     * 搜索栏省
     */
    var initProvinceSelect = function () {
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            type: "get",
            success: function (data) {
                var mySelect = document.getElementById("provinceSelect");
                mySelect.add(new Option("请选择", ''), 0);
                for (var i = 0; i < data.length; i++) {
                    var name = data[i].divisionName;
                    var code = data[i].divisionName;
                    mySelect.add(new Option(name, code));
                }
            }
        });
    };
	var initCityCountyNameConditionSelect = function () {
		$.ajax({
			url: getServer() + "/fxCityCountys/" + "getCityCountyNames",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("cityCountyNameCondition");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i];	
					var code = data[i];
					mySelect.add(new Option(name, code));
				}
				$('.selectpicker').selectpicker({'selectedText': 'cat'});
			}
		});
	};
	var initSurveySpotNameConditionSelect = function () {
		$.ajax({
			url: getServer() + "/fxSurveySpots/" + "getSurveySpotNames",
			type: "get",
			success: function (data) {
				debugger;
				var mySelect = document.getElementById("surveySpotNameCondition");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i];	
					var code = data[i];
					mySelect.add(new Option(name, code));
				}
				$('.selectpicker1').selectpicker({'selectedText': 'cat'});
			}
		});
	};
	var initCityCountyNameSelect = function () {
		$.ajax({
			url: getServer() + "/fxCityCountys/" + "getCityCountyNames",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("cityCountyName");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i];	
					var code = data[i];
					mySelect.add(new Option(name, code));
				}
				$('.selectpicker').selectpicker({'selectedText': 'cat'});
			}
		});
	};
	var initSurveySpotNameSelect = function () {
		$.ajax({
			url: getServer() + "/fxSurveySpots/" + "getSurveySpotNames",
			type: "get",
			success: function (data) {
				var mySelect = document.getElementById("surveySpotName");
				mySelect.add(new Option("请选择", ''), 0);
				for (var i = 0; i < data.length; i++) {
					var name = data[i];	
					var code = data[i];
					mySelect.add(new Option(name, code));
				}
				$('.selectpicker1').selectpicker({'selectedText': 'cat'});
			}
		});
	};
    // 添加表单省市区
    var initcreateProvinceForm = function () {
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }

    // 编辑表单省市区
    var editProvince = function (Province, City, Area) {
        debugger;
        var html = "";
        $("#city").append(html);
        $("#area").append(html);
        $.ajax({
            url: getServer() + "/divisions/root/subdivisions",
            contentType: "application/json",
            type: "get",
            success: function (data) {
                $.each(data, function (idx, item) {
                    if (item.divisionName == Province) {
                        debugger;
                        var divisionId = item.divisionId;
                        var htmlCity = '';
                        if (Province == "北京市" || Province == "天津市" || Province == "上海市" || Province == "重庆市") {
                            $("#city").append("<option value='" + Province + "' exid='" + divisionId + "'>" + Province + "</option>");
                            $('#city').val(City);
                            var htmlArea = '';
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    $.each(data, function (idx, item) {
                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#area").append(htmlArea);
                                    $('#area').val(Area);
                                }
                            });

                        } else {
                            $.ajax({
                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                contentType: "application/json",
                                type: "get",
                                success: function (data) {
                                    debugger;
                                    $.each(data, function (idx, item) {
                                        if (item.divisionName == City) {
                                            var divisionId = item.divisionId;
                                            var htmlArea = '';
                                            $.ajax({
                                                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                                                contentType: "application/json",
                                                type: "get",
                                                success: function (data) {
                                                    $.each(data, function (idx, item) {
                                                        htmlArea += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                                    });
                                                    $("#area").append(htmlArea);
                                                    $('#area').val(Area);
                                                }
                                            });
                                        }
                                        htmlCity += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                                    });
                                    $("#city").append(htmlCity);
                                    $('#city').val(City);
                                }
                            });
                        }
                    }
                    html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                });
                $("#province").append(html);
                $('#province').val(Province);
            }
        });
        $("#province").change(function () {
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#city option").remove();
            $("#city").append(html);
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            if ($(this).val() == "北京市" || $(this).val() == "天津市" || $(this).val() == "上海市" || $(this).val() == "重庆市") {
                $("#city").append("<option value='" + $(this).val() + "' exid='" + divisionId + "'>" + $(this).val() + "</option>");
                return;
            }
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#city").append(html);
                }
            });
        });
        $("#city").change(function () {
            if ($(this).val() == "") return;
            var html = '<option value="" disabled selected style="display:none;">请选择</option>';
            $("#area option").remove();
            $("#area").append(html);
            var divisionId = $(this).find("option:selected").attr("exid");
            $.ajax({
                url: getServer() + "/divisions/" + divisionId + "/subdivisions",
                contentType: "application/json",
                type: "get",
                success: function (data) {
                    $.each(data, function (idx, item) {
                        html += "<option value='" + item.divisionName + "' exid='" + item.divisionId + "'>" + item.divisionName + "</option>";
                    });
                    $("#area").append(html);
                }
            });
        });
    }

    var initSearchBlock = function () {
        SearchBlock.init("searchBlock");
    };

    var queryBtnBind = function () {
        $("#btnSearch").click(function () {
            createFxRescueGrid();
        });
        $("#btnReset").click(function () {
            $("#provinceCondition").val("");
            $('#cityCountyNameCondition').selectpicker('val',"");
           	$('#surveySpotNameCondition').selectpicker('val',"");
            
        });
    };

    var createFxRescueGrid = function () {
        $("#fxRescueGrid").datagrid({
            url: getFxRescueController() + "/queryFxRescues",
            method: "GET",
            fitColumns: true,
            autoRowHeight: false,
            columns: [[
                {field: "ck", checkbox: true},
                {
                    field: 'cityCountyName',
                    title: '市县名称',
                    width: '12.5%',
                    align: 'center',
                },
                {
                    field: 'surveySpotName',
                    title: '调查点名称',
                    width: '12.5%',
                    align: 'center',
                    formatter: function (value, rowData, rowIndex) {
                        return '<a href="#" onclick="_editFxRescue(\'' + rowData.id + '\');"> ' + rowData.surveySpotName + ' </a> '
                    }
                },
                {
                    field: 'province',
                    title: '省',
                    width: '12.5%',
                    align: 'center',
                },
                {
                    field: 'tent',
                    title: '帐篷',
                    width: '12.5%',
                    align: 'center',
                },
                {
                    field: 'quilt',
                    title: '棉被',
                    width: '12.5%',
                    align: 'center',
                },
                {
                    field: 'food',
                    title: '食品',
                    width: '12.5%',
                    align: 'center',
                },
                {
                    field: 'stretcher',
                    title: '担架',
                    width: '12%',
                    align: 'center',
                },
                {
                    field: 'rescueEquipment',
                    title: '救援装备',
                    width: '12%',
                    align: 'center',
                },
            ]],
            toolbar: [{
                iconCls: 'fa fa-plus-circle',
                text: "添加",
                handler: function () {
                    addFxRescue();
                }
            }, {
                iconCls: 'fa fa-plus-circle',
                text: "模板",
                handler: function () {
                    downloadTemplate();
                }
            }, {
                iconCls: 'fa fa-upload',
                text: "导入",
                handler: function () {
                    importForm();
                }
            }, {
                iconCls: 'fa fa-download',
                text: "导出",
                handler: function () {
                    exportForm();
                }
            }, {
                iconCls: 'fa fa-trash-o',
                text: "删除",
                handler: function () {
                    deleteFxRescue();
                }
            }],
            queryParams: {
                province: $("#provinceSelect").val(),
                cityCountyName: $("#cityCountyNameCondition").val(),
                surveySpotName: $("#surveySpotNameCondition").val(),
            },
            pagination: true,
            pageSize: 10
        });
    };
    var formValidator = function () {
        $("#fxRescueForm").validate({
            rules: {
                province: {
                    required: true,
                },
                city: {
                    required: true,
                },
                area: {
                    required: true,
                },
                cityCountyName: {
                    required: true,
                    number: true
                },
                surveySpotName: {
                    required: true,
                    number: true
                },
                tent: {
                    required: true,
                    number: true
                },
                quilt: {
                    required: true,
                    number: true
                },
                cottonClothes: {
                    required: true,
                    number: true
                },
                food: {
                    required: true,
                    number: true
                },
                water: {
                    required: true,
                    number: true
                },
                stretcher: {
                    required: true,
                    number: true
                },
                rescueEquipment: {
                    required: true,
                    number: true
                },
                rescueEquipment: {                   
                    number: true
                },
                fireControl: {                   
                    number: true
                },
                army: {                   
                    number: true
                },
                volunteer: {                   
                    number: true
                },
                otherRescue: {                   
                    number: true
                },
                shelterNum: {                   
                    number: true
                },
                shelterArea: {                   
                    number: true
                },
                shelterContainPopulation: {                   
                    number: true
                },
                medicalCare: {                   
                    number: true
                },
            },
            messages: {
                province: {
                    required: "省不允许为空!",
                },
                city: {
                    required: "市不允许为空!",
                },
                area: {
                    required: "区不允许为空!",
                },
                cityCountyName: {
                    required: "市县名称不允许为空!",
                },
                surveySpotName: {
                    required: "调查点名称不允许为空!",
                },
                tent: {
                    required: "帐篷不允许为空!",
                },
                quilt: {
                    required: "棉被不允许为空!",
                },
                cottonClothes: {
                    required: "棉服不允许为空!",
                },
                food: {
                    required: "食品不允许为空!",
                },
                water: {
                    required: "饮水不允许为空!",
                },
                stretcher: {
                    required: "担架不允许为空!",
                },
                rescueEquipment: {
                    required: "救援装备不允许为空!",
                },
            }
        });
    };
    var getFxRescue = function (id) {
        $.ajax({
            url: getFxRescueController() + "/" + id,
            type: "get",
            success: function (data) {
            	$('#cityCountyName').selectpicker('val',data.cityCountyName);
            	$('#surveySpotName').selectpicker('val',data.surveySpotName);
                editProvince(data.province, data.city, data.area);
                Tool.deserialize("fxRescueForm", data);
            }
        });
    };

    var addFxRescue = function () {
        var slidebar = Util.slidebar({
            url: fxRescueFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                initcreateProvinceForm();
                initCityCountyNameSelect();
                initSurveySpotNameSelect();
                formValidator();
                $("#saveBtn").on("click", function () {
                    if ($("#fxRescueForm").valid()) {
                        var data = Tool.serialize("fxRescueForm");
                        $.ajax({
                            url: getFxRescueController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "post",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxRescueGrid();
                            }
                        });
                    }
                });
            }
        });
    };

    /**
     * 下载模板
     */
    var downloadTemplate = function () {
        window.location.href = getServer() + "/excel/市县救援数据模板.xlsx";
    };

    /**
     * 导入
     */
    var importForm = function () {
        // 模板下载
        $("#uploadModal").modal();
        $("#uploadModal").on("shown.bs.modal", function () {
            var url = getServer() + "/excel/市县救援数据模板.xlsx";
            $("#downloadZwExcelTemplate").attr("href", url);
        });
        $('#uploadButton').off("click");
        $("#uploadButton").on("click", function () {
            var uploadinput = document.getElementById("uploadFile");
            if (uploadinput.value == "") {
                Util.alert("上传前请先选择文件!");
                return;
            }
            var formData = new FormData();
            formData.append("file", uploadinput.files[0]);
            $.ajax({
                url: getFxRescueController() + "/import",
                data: formData,
                processData: false, //因为data值是FormData对象，不需要对数据做处理。
                contentType: false,
                type: "POST",
                success: function (data) {
                    $('#uploadModal').modal('hide');
                    uploadinput.value = null;
                    createFxRescueGrid();
                    Util.alert(data);
                }
            });
        });
    };

    /**
     * 导出
     */
    var exportForm = function () {
        let province = $("#provinceSelect").val();
        let cityCountyName = $("#cityCountyNameCondition").val();
        let surveySpotName = $("#surveySpotNameCondition").val();
        window.location.href = getFxRescueController() + "/export?province=" + province + "&cityCountyName=" + cityCountyName
            + "&surveySpotName=" + surveySpotName;
    };

    window._editFxRescue = function (fxRescueId) {
        var slidebar = Util.slidebar({
            url: fxRescueFormHtml,
            width: "800px",
            cache: false,
            close: true,
            afterLoad: function () {
                formValidator();
                initCityCountyNameSelect();
                initSurveySpotNameSelect();
                getFxRescue(fxRescueId);
                $("#saveBtn").on("click", function () {
                    if ($("#fxRescueForm").valid()) {
                        var data = Tool.serialize("fxRescueForm");
                        $.ajax({
                            url: getFxRescueController(),
                            contentType: "application/json",
                            data: JSON.stringify(data),
                            type: "put",
                            success: function (data) {
                                Util.alert(data.message);
                                slidebar.close();
                                createFxRescueGrid();
                            }
                        });
                    }
                });
            }
        });
    };
    var deleteFxRescue = function () {
        var rows = $("#fxRescueGrid").datagrid("getSelections");
        if (rows == null || rows.length == 0) {
            Util.alert("请选择一行数据!");
            return;
        }
        Util.confirm("是否要删除选中的数据?", function () {
            var ids = "";
            $.each(rows, function (i, row) {
                ids += row.id + ",";

            });
            ids = ids.substr(0, ids.length - 1);
            $.ajax({
                url: getFxRescueController(),
                data: {
                    ids: ids
                },
                type: "delete",
                success: function (data) {
                    createFxRescueGrid();
                }
            });
        }, function () {
            return;
        });

    };

    return {
        init: init
    };
});
